﻿using B.S.GridManage.Domain.Entities;
using B.S.GridManage.Infrastructure.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace B.S.GridManage.Infrastructure.Implement
{
    /// <summary>
    /// 仓储实现
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T> : IBaseRepository<T> where T :BaseEntity
    {
        private readonly ScDbContext db;
        /// <summary>
        /// 通过构造函数注入数据库上下文
        /// </summary>
        /// <param name="db"></param>
        public BaseRepository(ScDbContext db)
        {
            this.db = db;
        }

        public async Task<int> AddRangeAsync(List<T> entities)
        {
           await db.Set<T>().AddRangeAsync(entities);
            return await  db.SaveChangesAsync();
        }

        /// <summary>
        /// 新增实体
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public Task<int> CreateAsync(T t)
        {
            db.Set<T>().AddAsync(t);
            return db.SaveChangesAsync();
        }
        /// <summary>
        /// 返回所有实体所有数据表达式,并没有实际执行
        /// </summary>
        /// <returns></returns>
        public IQueryable<T> GetAll()
        {
            return db.Set<T>();
        }

        public async Task<T> GetModel(long id)
        {
            return await db.Set<T>().FindAsync(id);
        }

        /// <summary>
        /// 更新实体
        /// </summary>
        /// <param name="t">实体对象</param>
        /// <returns>受影响的行数任务</returns>
        public Task<int> UpdateAsync(T t)
        {
            db.Set<T>().Update(t);
            return db.SaveChangesAsync();
        }
    }
}
